<?php
namespace app\user\logic\user;

use app\common\exception\LogicException;
use app\course\logic\base\Course;
use app\course\logic\classes\Classes;
use app\course\logic\coupon\Coupon;
use app\user\model\user\Cart as CartModel;

/**
 * 购物车管理
 */
class Cart extends CartModel
{

    /* 购物车数量 */
    public function getNum()
    {
        return $this->scope('mid')->count() ?: 0;
    }

    /* 购物车页面 */
    public function cartFetch()
    {
        $cart = $this->scope('fetch')->with(['school_name'])->select();

        // 按机构重组数组
        $data = [];
        foreach ($cart as $v) {
            $mhm_id                        = $v->mhm_id;
            $data[$mhm_id]['mhm_id']       = $mhm_id;
            $data[$mhm_id]['school_name']  = $v->school_name;
            $data[$mhm_id]['course_ids'][] = $v->course_id;
        }
        foreach ($data as &$d) {
            $course_ids = implode(',', $d['course_ids']);
            unset($d['course_ids']);
            $d['course_list'] = app(Course::class)
                ->field('id,cover,title,price,vip_price,term_time,mhm_id,course_type,solo')
                ->with(['cover_url'])
                ->withCount(['section_count'])
                ->where('id', 'IN', $course_ids)
                ->orderRaw("FIND_IN_SET(id,'{$course_ids}')")
                // ->buildSql()
                ->select()
                ->append(['course_type_text', 'user_price'])
                ->each(function ($i) {
                    if ($i->course_type == 4) {
                        $i->section_count_count = app(Classes::class)->getClassesSectionCount($i->id);
                    }
                    $i->has_course_card = app(Coupon::class)->userHasDerivedCourseCard($i->id);
                })
            ;
            unset($d);
        }
        return array_values($data);
    }

    // 添加商品到购物车
    public function cartAdd($param)
    {
        // 验证数据
        $this->getValidate()->scene('cart_add')->failException()->check($param);
        // 参数
        $course_id = $param['course_id'];
        $mid       = request()->mid;
        // 检查购物车商品是否存在
        $exist = $this->where('user_id', $mid)->where('course_id', $course_id)->findOrEmpty();

        if ( !$exist->isEmpty() ) throw new LogicException('已加入购物车');
        // 检测商品是否存在
        $course = app(Course::class)->findOrFail($course_id);

        $re = $this::create([
            'user_id'   => $mid,
            'course_id' => $course_id,
            'mhm_id'    => $course->mhm_id,
        ]);

        if ($re->isEmpty()) throw new LogicException("加入失败");

        return $re;
    }

    // 移除购物车商品
    public function cartDelete($param)
    {
        $ids   = $param['course_ids'];
        $datas = $this->scope('mid')->where('course_id', 'IN', $ids)->select();

        if (!$datas->delete()) throw new LogicException('移除失败');

        return $ids;
    }

}
